package org.dromara.nursing.service.impl;

import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.dromara.nursing.domain.bo.FoodServiceBo;
import org.dromara.nursing.domain.bo.ElderOutstandingFeesBo;
import org.dromara.nursing.domain.vo.FoodServiceVo;
import org.dromara.nursing.domain.FoodService;
import org.dromara.nursing.mapper.FoodServiceMapper;
import org.dromara.nursing.service.IFoodServiceService;
import org.dromara.nursing.service.IElderOutstandingFeesService;

import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.Calendar;
import java.util.Collection;

/**
 * 饮食服务Service业务层处理
 *
 * @author Xue
 * @date 2025-04-09
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class FoodServiceServiceImpl implements IFoodServiceService {

    private final FoodServiceMapper baseMapper;
    private final IElderOutstandingFeesService elderOutstandingFeesService;

    /**
     * 查询饮食服务
     *
     * @param serviceId 主键
     * @return 饮食服务
     */
    @Override
    public FoodServiceVo queryById(Long serviceId){
        return baseMapper.selectVoById(serviceId);
    }

    /**
     * 分页查询饮食服务列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 饮食服务分页列表
     */
    @Override
    public TableDataInfo<FoodServiceVo> queryPageList(FoodServiceBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<FoodService> lqw = buildQueryWrapper(bo);
        Page<FoodServiceVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的饮食服务列表
     *
     * @param bo 查询条件
     * @return 饮食服务列表
     */
    @Override
    public List<FoodServiceVo> queryList(FoodServiceBo bo) {
        LambdaQueryWrapper<FoodService> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<FoodService> buildQueryWrapper(FoodServiceBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<FoodService> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(FoodService::getServiceId);
        lqw.like(StringUtils.isNotBlank(bo.getMealName()), FoodService::getMealName, bo.getMealName());
        lqw.eq(StringUtils.isNotBlank(bo.getMealType()), FoodService::getMealType, bo.getMealType());
        lqw.like(StringUtils.isNotBlank(bo.getElderName()), FoodService::getElderName, bo.getElderName());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), FoodService::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增饮食服务
     *
     * @param bo 饮食服务
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public FoodServiceVo insertByBo(FoodServiceBo bo) {
        try {
            // 1. 插入饮食服务记录
            FoodService add = MapstructUtils.convert(bo, FoodService.class);
            validEntityBeforeSave(add);
            boolean flag = baseMapper.insert(add) > 0;
            if (flag) {
                bo.setServiceId(add.getServiceId());

                // 2. 如果有服务费用，创建欠费记录
                if (bo.getServiceFee() != null && bo.getServiceFee() > 0) {
                    createOutstandingFee(bo);
                }

                // 3. 返回新创建的饮食服务记录
                return queryById(add.getServiceId());
            }
            return null;
        } catch (Exception e) {
            log.error("新增饮食服务失败", e);
            throw e;
        }
    }

    /**
     * 创建欠费记录
     *
     * @param foodServiceBo 饮食服务信息
     */
    private void createOutstandingFee(FoodServiceBo foodServiceBo) {
        // 创建欠费记录
        ElderOutstandingFeesBo feesBo = new ElderOutstandingFeesBo();
        feesBo.setElderId(foodServiceBo.getElderId());
        feesBo.setElderName(foodServiceBo.getElderName());
        feesBo.setFeeSource("餐饮费");
        feesBo.setSourceId(foodServiceBo.getServiceId());
        feesBo.setBillDate(new Date()); // 当前日期作为计费日期

        // 设置应付日期（默认30天后）
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, 30);
        feesBo.setDueDate(calendar.getTime());

        feesBo.setTotalAmount(foodServiceBo.getServiceFee());
        feesBo.setPaidAmount(0L); // 初始已付金额为0
        feesBo.setOutstandingAmount(foodServiceBo.getServiceFee()); // 初始未付金额等于总金额
        feesBo.setPaymentStatus(foodServiceBo.getPaymentStatus() != null ? foodServiceBo.getPaymentStatus() : "未支付");
        feesBo.setIsOverdue("0"); // 初始设置为未逃期
        feesBo.setOverdueDays(0L);
        feesBo.setReminderCount(0L);
        feesBo.setRemarks(foodServiceBo.getRemarks());

        // 保存欠费记录
        elderOutstandingFeesService.insertByBo(feesBo);
    }

    /**
     * 修改饮食服务
     *
     * @param bo 饮食服务
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(FoodServiceBo bo) {
        FoodService update = MapstructUtils.convert(bo, FoodService.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(FoodService entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除饮食服务信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
